package org.xs.web.http;

import java.io.IOException;
import java.io.Writer;

import org.xs.web.http.provider.HTTPHeader;
import org.xs.web.http.provider.HTTPResponse;
import org.xs.web.http.velocity.LayoutFactory;
import org.xs.web.util.Helpers;

public class HtmlResponse implements XSResponse{
	private XSResponse notfound = new NotfoundResponse("Template not found");
	private int code;
	private String contentType;
	private HTTPHeader[] headers;
	private String name;
	
	public HtmlResponse(String name,int code ,String contentType,HTTPHeader[] headers){
		this.name = name.replaceAll("\\.\\w+", "");
		this.contentType = contentType;
		this.headers = headers;
		this.code = code;
	}
	public HtmlResponse(String name){
		this(name,200,"text/html;charset=utf-8",new HTTPHeader[0]);
	}
	
	public HtmlResponse(String name,int code){
		this(name,code,"text/html;charset=utf-8",new HTTPHeader[0]);
	}
	public HtmlResponse(String name,String contentType){
		this(name,200,contentType,new HTTPHeader[0]);
	}
	public HtmlResponse(String name,HTTPHeader[] headers){
		this(name,200,"text/html;charset=utf-8",headers);
	}
	
	public HtmlResponse(String name,int code,HTTPHeader[] headers){
		this(name,code,"text/html;charset=utf-8",headers);
	}
	
	@Override
	public int getCode() {
		return 0;
	}

	@Override
	public String getContentType() {
		return null;
	}

	@Override
	public HTTPHeader[] getHeaders() {
		return null;
	}

	@Override
	public boolean isJs() {
		return false;
	}

	@Override
	public boolean isStream() {
		return false;
	}

	@Override
	public boolean isTemplete() {
		return true;
	}

	@Override
	public boolean isText() {
		return false;
	}

	@Override
	public boolean isXml() {
		return false;
	}

	@Override
	public Object apply(HTTPResponse response) {
		String templateName = XSRules.mergeTemplateName(name);
		if(Helpers.inArray(XSRules.defaultLayout, templateName)){
			notfound.apply(response);
			return true;
		}
		
		String layoutContextAsString = LayoutFactory.layout(XSRules.velocityEngine, templateName,S.getContext());
		response.addHeader("Content-Length", String.format("%s", new Object[]{layoutContextAsString.getBytes().length}));
		response.addHeader("Content-Type", contentType);
		Writer write = null;
		try {
			write = response.getDelegate().getWriter();
			write.write(layoutContextAsString);
		} catch (Exception e) {
		}finally{
			if(write != null){
				try {
					write.flush();
					write.close();
				} catch (IOException e) {
				}
			}
		}
		return true;
	}
}
